package com.gopay.bis.manager.bank.ebank;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.TransUtils;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.bos.ebank.BosB2cMessage;
import com.gopay.common.domain.user.mcc.UserMccTransformReq;
import com.gopay.common.domain.user.mcc.UserMccTransformRes;
import com.gopay.common.exception.GopayException;
import com.gopay.common.user.mcc.manager.UserMccTransformManager;
import com.gopay.remote.bank.BankManagerRemoteService;
import com.gopay.remote.bank.businesses.BankService;

public class BosB2cManager implements BankManagerRemoteService {
	
	@Resource(name = "bosB2cBankServiceClient")
	private BankService bosB2cBankServiceClient;
	
	@Resource(name = "bosB2cBankServiceClientHna")
	private BankService bosB2cBankServiceClientHna;
	 
	@Resource(name = "bosConfig")
	private Map<String, String> bosConfig; 
	
	@Resource(name = "userMccTransformManager")
	private UserMccTransformManager userMccTransformManager;
	 
	@Override
	public Object sign(BaseMessage msg) throws GopayException {
		UserMccTransformReq userM = new UserMccTransformReq();
		userM.setBankCode(BankConstants.BANK_LOGO_BOS);
		userM.setCustId(msg.getSpecial2());
		UserMccTransformRes userRes = userMccTransformManager.graspUserMccInfo(userM);
		BosB2cMessage message = (BosB2cMessage)msg;
		String orderAmt = message.getAmount().toString();
		// 金额以分为单位
		message.setMerOrderAmt(TransUtils.amountConvert2Fen(orderAmt));
		
		message.setCurType((String) bosConfig.get("BOS.B2C.CURTYPE"));
		message.setMerNotifyUrl(message.getPayRuturnUrl());
		message.setMerNotifySign((String) bosConfig.get("BOS.B2C.MERNOTIFYSIGN"));
		message.setMerGetGoodsUrl(message.getPayNotifyUrl());
		message.setMerGetGoodsSign((String) bosConfig.get("BOS.B2C.MERGETGOODSSIGN"));
		if (!message.isSupportCredit()) {
			//充值
			message.setMerchantID(message.getMerID2nd());
			message.setReserved1("11");
		}else{
			//支付
			message.setMerchantID(message.getMerID());
			message.setReserved1("00");
		}
		
		if (userRes == null) {
			if ((BankConstants.GOPAY_CHONGZHI_CUSTID).equals(msg.getSpecial2())) {
				message.setShortcutMerCode(BankConstants.GOPAY_CODE);
				message.setPayeeMerchantName(BankConstants.GOPAY_NAME);
			}
		} else {
			String subMerId = "" + userRes.getProvince() + "" + userRes.getBankMccCode() + "" + userRes.getGopayMccNum();
			message.setShortcutMerCode(subMerId);
			message.setPayeeMerchantName(userRes.getCorpName());
		}
		message.setShopName("");
		message.setProductName("");
		message.setProductProperty("");
		message.setConsigneeName("");
		message.setConsigneeAddress("");
		message.setIsGlobal("Y");
		message.setNational("CN");
		message.setMerchantWebInfo("www.gopay.com.cn");
		message.setTerminalType("PC");
		message.setMainPage("www.gopay.com.cn");
		message.setBankUrl(message.getPayUrl());
		message.setOrderDT(this.getCurrDate().substring(0,8));
		message.setOrderTime(this.getCurrDate().substring(8));
		String plainStr = buildPlainB2C(message);// 原文
		message.setSignDataStr(plainStr);
		BankLogUtils.printB2CManagerSignSendLog(message);
		if(message.isHna()){
	        message = (BosB2cMessage) bosB2cBankServiceClientHna.sign(message);
	    }else{
	    	message = (BosB2cMessage)bosB2cBankServiceClient.sign(message);// 签名
	    }
		BankLogUtils.printB2CManagerSignReturnLog(message);
		return message;
	}
	
	@Override
	public Object verify(BaseMessage msg) throws GopayException {
		BosB2cMessage message = (BosB2cMessage)msg;
		BankLogUtils.printB2CManagerVerifySendLog(message);
		String plainStr=buildVerifyPlain(message);
		message.setSignDataStr(plainStr);
		boolean flag;
		if(message.isHna()){
	        flag = (Boolean) bosB2cBankServiceClientHna.verify(message);
	    }else{
		    flag = (Boolean)bosB2cBankServiceClient.verify(message);
	    }
		BankLogUtils.printB2CManagerVerifyReturnLog(message, flag);
		return flag;
	}

	@Override
	public Object query(Object obj) throws GopayException {
		BosB2cMessage reqQueryMsg = (BosB2cMessage)obj;
		if(BisPayCheckUtils.checkExternalOrderID(reqQueryMsg.getOrderId())){
			reqQueryMsg.setOrderBeginDate(reqQueryMsg.getOrderDate().toString());
			reqQueryMsg.setOrderEndDate(reqQueryMsg.getOrderDate().toString());
			reqQueryMsg.setOrderList(reqQueryMsg.getOrderId());
		}
		reqQueryMsg = buildQueryB2C(reqQueryMsg);
		BankLogUtils.printB2CManagerQuerySendLog(reqQueryMsg, "");
		BosB2cMessage resQueryMsg;
		 if(reqQueryMsg.isHna()){
			 resQueryMsg = (BosB2cMessage) bosB2cBankServiceClientHna.query(reqQueryMsg);
		 }else{
		      resQueryMsg = (BosB2cMessage) bosB2cBankServiceClient.query(reqQueryMsg);
		 }
		resQueryMsg.setOutStlmCd(BankConstants.BANK_LOGO_BOS);
		BankLogUtils.printB2CManagerQueryReturnLog(resQueryMsg);
		return resQueryMsg;
	}

	/**
	 * 构建B2C报文
	 * 
	 * @param message
	 *            上海银行B2C数据结构体
	 * @return String 商户签名源数据
	 */
	public String buildPlainB2C(BosB2cMessage message) {
		StringBuffer sb = new StringBuffer("");
		sb.append(message.getMerchantID()).append("|")
		.append(message.getOrderId()).append("|")
		.append(message.getMerOrderAmt()).append("|")
		.append(message.getCurType());
		return sb.toString();
	}
	

	/**
	 * 构建验签报文
	 * 
	 * @param message
	 *            上海银行B2C数据结构体
	 * @return String 商户签名源数据
	 */
	public String buildVerifyPlain(BosB2cMessage message) {
		StringBuffer sb = new StringBuffer("");
		sb.append(message.getMerchantID()).append("|")
		.append(message.getOrderId()).append("|")
		.append(message.getMerOrderAmt()).append("|")
		.append(message.getCurType()).append("|")
		.append(message.getTranSerialNo()).append("|")
		.append(message.getTranResult());
		return sb.toString();
	}
	
	/**
	 * B2C订单查询请求对象拼装
	 * 
	 * @param messageB2C
	 * @return
	 */
	public BosB2cMessage buildQueryB2C(BosB2cMessage messageB2C) {
		if (!messageB2C.isSupportCredit()) {
			//充值
			messageB2C.setMerchantID(messageB2C.getMerID2nd());
		}else{
			//支付
			messageB2C.setMerchantID(messageB2C.getMerID());
		}
		
		// 组装签名源数据
		StringBuffer sb = new StringBuffer("");
		sb.append(messageB2C.getMerchantID()).append("|")
		.append(messageB2C.getOrderList()).append("|")
		.append(messageB2C.getOrderBeginDate()).append("|")
		.append(messageB2C.getOrderEndDate());
		messageB2C.setSignDataStr(sb.toString());
		return messageB2C;
	}
	/**
	 * 获取当前时间
	 * 
	 * @return String
	 */
	private String getCurrDate() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String s = sdf.format(date);
		return s;
	}

	@Override
	public Object dayend(BaseMessage base) throws GopayException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object refund(BaseMessage base) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}
}
